import gdata.docs
import gdata.docs.service
import os.path

class GDoc(object):
    def __init__(self, email, password,workspace):
        source = 'vim gdoc'
        self.workspace=workspace
        self.gd_client = gdata.docs.service.DocsService()
        self.gd_client.ClientLogin(email, password, source=source)

    def get_doc_entry(self,name):
        q = gdata.docs.service.DocumentQuery()
        q['title'] = name
        q['title-exact'] = 'true'
        feed = self.gd_client.Query(q.ToUri())
        if not feed.entry :
            return None
        return feed.entry[0]

    def load_doc(self,name):
        entry=self.get_doc_entry(name)
        if not entry : return
        file_path=os.path.join(self.workspace, name)
        self.gd_client.Download(entry.resourceId.text, file_path,"txt")
        lines=open(file_path).readlines()
        for line in lines :
            print line
        os.remove(file_path)
        return lines

    def save_doc(self,name,lines):
        entry = self.get_doc_entry(name)
        content_type=gdata.docs.service.SUPPORTED_FILETYPES['DOC']
        file_path=os.path.join(self.workspace,"gdoc.txt")
        tmpfile=open(file_path, "w")
        for line in lines:
            tmpfile.write(line+"\n")
        tmpfile.close()
        ms = gdata.MediaSource(file_path=file_path, content_type=content_type)
        if not entry :
            entry = self.gd_client.Upload(ms, name)
        else :
            entry = self.gd_client.Put(ms, entry.GetEditMediaLink().href)
        del ms
        os.remove(file_path)
        return True

def inputUser():
    print "please input gmail account and password"
    vim.command("let b:gmail_user=input('')")
    vim.command("let b:gmail_password=input('')")
    user=vim.eval("b:gmail_user")
    password=vim.eval("b:gmail_password")
    return user,password
    

def GdocSave(name):
    user,password=inputUser()
    gdoc=GDoc(user,password,sztool_data_home)
    buffer=vim.current.buffer
    lines=[line for line in buffer]
    gdoc.save_doc(name,lines)
    
def GdocLoad(name):
    user,password=inputUser()
    gdoc=GDoc(user,password,sztool_data_home)
    lines=gdoc.load_doc(name)
    buffer=[]
    for line in lines :
        line=unicode(line,"utf-8")
        codepage=sys.getdefaultencoding()
        buffer.append(line.encode(codepage,"replace"))
    output(buffer)
        

